//
//  MyCarViewController.m
//  LocomotiveGuards
//
//  Created by zwj on 15-11-30.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "MyCarViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "UIImageView+WebCache.h"
#import "LoginViewController.h"
#import "AlertView.h"

@interface MyCarViewController () <UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UIButton *_rightBtn;
    UIView *_imageBgView;
    UIImageView *_carImageView;
    UILabel *_tipLabel;
    NSDictionary *_listDic;
    NSArray *_labelArray;
    UIButton *_uploadBtn;
    UIButton *_changeBtn;
    UIView *_scaleView;
    NSInteger _flag;
}

@property (nonatomic, strong) NSString *userOrTourist;

@end

@implementation MyCarViewController
- (instancetype)init {
    self = [super init];
    if (self) {
        _listDic = [NSDictionary new];
        _labelArray = @[@"车牌号",@"品牌",@"颜色",@"设备号",@"保险时效"];
        _flag = 0;
    }
    return self;
}

- (void)dealloc
{
    NSLog(@"释放对象 %@",[self class]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.userOrTourist = [[NSUserDefaults standardUserDefaults] objectForKey:@"userOrTourist"];
    [self createMyNav];
    [self configView];
    if ([self.userOrTourist isEqualToString:@"1"]) {
        [self getCarMessageRequest];

    }
}

- (void)createMyNav
{
    UIImageView *imgView = [self addTitle:@"我的车辆" imageName:@"car"];
    imgView.frame = CGRectMake((SCREEN_WIDTH-(15+5+70)*W)/2, 20+19*H, 15*W, 10*H);
    [self addBackBtnTarget:self action:@selector(backBtnClick)];
    _rightBtn = [self addRightBtnTarget:self action:@selector(edit:)];
}

- (void)configView
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 20+44*H, SCREEN_WIDTH, 5*35*H)];
    bgView.backgroundColor = [UIColor colorWithRed:247.f/255.f green:248.f/255.f blue:248.f/255.f alpha:1.0f];
//    bgView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:bgView];
    
    for (int i=0; i<5; i++) {
        UILabel *messLabel = [self createLabelFrame:CGRectMake(30*W, 35*H*i, SCREEN_WIDTH, 35*H-1) title:_labelArray[i] font:[UIFont systemFontOfSize:14]];
        messLabel.textColor = [UIColor grayColor];
        messLabel.textAlignment = NSTextAlignmentLeft;
        messLabel.backgroundColor = [UIColor clearColor];
        messLabel.tag = 200+i;
        [bgView addSubview:messLabel];
        
        UILabel *separateLabel = [self createLabelFrame:CGRectMake(0, 35*H*(i+1)-1, SCREEN_WIDTH, 1) title:nil font:nil];
        separateLabel.backgroundColor = [UIColor colorWithRed:230.f/255.f green:230.f/255.f blue:230.f/255.f alpha:1.0f];
        [bgView addSubview:separateLabel];
    }
    
    UILabel *carLabel = [self createLabelFrame:CGRectMake((SCREEN_WIDTH-100*W)/2, CGRectGetMaxY(bgView.frame)+12*H, 100*W, 30*H) title:@"电动车照片" font:[UIFont systemFontOfSize:15]];
    carLabel.textColor = [UIColor grayColor];
    [self.view addSubview:carLabel];
    
    _imageBgView = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-260*W)/2, CGRectGetMaxY(carLabel.frame)+10*H, 260*W, 167*H)];
    [_imageBgView setBackgroundColor:[UIColor colorWithRed:230.f/255.f green:230.f/255.f blue:230.f/255.f alpha:1.0f]];
    CALayer *viewLayer = _imageBgView.layer;
    [viewLayer setMasksToBounds:YES];
    viewLayer.cornerRadius = 14;
    
    _carImageView = [[UIImageView alloc] init];
    _carImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_carImageView addGestureRecognizer:g];
    [_imageBgView addSubview:_carImageView];
    
    _tipLabel = [self createLabelFrame:CGRectMake(0, CGRectGetHeight(_imageBgView.frame)/2-30*H, CGRectGetWidth(_imageBgView.frame), 30*H) title:@"请上传一张车辆全身照,便于车辆被盗搜索" font:[UIFont systemFontOfSize:13]];
    _tipLabel.textColor = [UIColor grayColor];
    [_imageBgView addSubview:_tipLabel];
    
    _uploadBtn = [self createBtnFrame:CGRectMake((CGRectGetWidth(_imageBgView.frame)-104*W)/2, CGRectGetHeight(_imageBgView.frame)/2+10*H, 104*W, 34*H) title:nil bgImageName:@"upload_pictures" selectedImageName:@"upload_pictures_on" target:self action:@selector(uploadCarPic)];
    [_imageBgView addSubview:_uploadBtn];
    _uploadBtn.hidden = YES;
    [self.view addSubview:_imageBgView];
    
    _changeBtn = [self createBtnFrame:CGRectMake((SCREEN_WIDTH-104*W)/2, CGRectGetMaxY(_imageBgView.frame)+10*H, 104*W, 34*H) title:nil bgImageName:@"12pic_btn01" selectedImageName:@"12pic_btn02" target:self action:@selector(changeCarPic)];
    [self.view addSubview:_changeBtn];
    _changeBtn.hidden = YES;
}

//数据下载完成，重新刷新界面显示
- (void)reloadView
{
    if (!_listDic) {
        return;
    }
    
    NSLog(@"我的车辆   %@",_listDic);
    NSMutableArray *tempArray = [@[[_listDic objectForKey:@"plateNum"],
                                  [_listDic objectForKey:@"brand"],
                                  [_listDic objectForKey:@"color"],
                                  [_listDic objectForKey:@"simId"],
                                   @"2016.07.16-2017.07.16"
                    
                                   ] mutableCopy];
    
    
    //把<null>转换成空字符串
    for (int i=0; i<tempArray.count; i++) {
        if ([tempArray[i] isKindOfClass:[NSNull class]]) {
            tempArray[i] = @"";
        }
    }
    
    _labelArray = @[
                    [NSString stringWithFormat:@"车牌号  %@",tempArray[0]],
                    [NSString stringWithFormat:@"品牌  %@",tempArray[1]],
                    [NSString stringWithFormat:@"颜色  %@",tempArray[2]],
                    [NSString stringWithFormat:@"设备号  %@",tempArray[3]],
                    [NSString stringWithFormat:@"保险(有效期)  %@",tempArray[4]]
                    ];
    
    for (int i=0; i<5; i++) {
        UILabel *label = (UILabel *)[self.view viewWithTag:200+i];
        label.text = _labelArray[i];
    }
    
    NSString *picStr = [_listDic objectForKey:@"picUrl"];
    if (![picStr isKindOfClass:[NSNull class]]) {
        //查询本地是否存在该图片，如果存在直接从本地加载图片,否则从网络获取
        NSString *fileName = [[[_listDic objectForKey:@"picUrl"] componentsSeparatedByString:@"/"] lastObject];
        NSString *dirPath = [[NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"] stringByAppendingString:fileName];
        UIImage *image = [UIImage imageWithContentsOfFile:dirPath];
        if (!image) {
            [self downloadImage];
        }
        else {
            CGFloat rate = image.size.width/image.size.height;
            if (rate > 1) {
                _carImageView.frame = _imageBgView.bounds;
            }
            else {
                _carImageView.frame = CGRectMake((CGRectGetWidth(_imageBgView.frame)-rate*167*H)/2, 0, rate*167*H, 167*H);
            }
            [_carImageView setImage:image];
        }
        _tipLabel.hidden = YES;
    }
    else {
        _tipLabel.hidden = NO;
    }
    _flag = 0;
}

- (void)downloadImage
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *urlStr = [@"https://appif.jszhtech.com:8443/ebappif/upImg/" stringByAppendingString:[_listDic objectForKey:@"picUrl"]];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [[UIImage alloc] init];
            if (data) {
                image = [UIImage imageWithData:data];
            }
            else {
                image = [UIImage imageNamed:@"car_default"];
            }
            
            CGFloat rate = image.size.width/image.size.height;
            if (rate > 1) {
                _carImageView.frame = _imageBgView.bounds;
            }
            else {
                _carImageView.frame = CGRectMake((CGRectGetWidth(_imageBgView.frame)-rate*167*H)/2, 0, rate*167*H, 167*H);
            }
            [_carImageView setImage:image];
            
            //图片下载后存放在本地
            NSString *fileName = [[[_listDic objectForKey:@"picUrl"] componentsSeparatedByString:@"/"] lastObject];
            NSString *dirPath = [[NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"] stringByAppendingString:fileName];
            NSLog(@"dirPath --> %@", dirPath);
            [data writeToFile:dirPath atomically:NO];
        });
    });
}

#pragma mark - 网络请求
//获取车辆信息
- (void)getCarMessageRequest
{
    _flag = 2;
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSDictionary *paramdic = @{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"]};
    NSString *url = [urlstring stringByAppendingString:@"getEbicycleInfo.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        if (flag == 0) {
            _listDic = [[dic objectForKey:@"bicycleLists"] firstObject];
            [self reloadView];
        }

    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

//上传车辆照片网络请求
- (void)uploadCarPicRequest
{
    _flag = 1;
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSData *carPicData = UIImageJPEGRepresentation(_carImageView.image, 0.5);

    NSDictionary *paramdic = @{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"],
                             @"bid":[[NSUserDefaults standardUserDefaults] objectForKey:@"bid"]
                             };
    NSString *url = [urlstring stringByAppendingString:@"uploadEbicyclePic.do"];
    
    [K_AppDelegate UploadHTTPRequestWithUrl:url withParam:paramdic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:carPicData name:@"ebicyclePic" fileName:@"file" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        NSString *picUrl = [dic objectForKey:@"picUrl"];

        if (flag == 0) {
            //上传成功
            NSLog(@"上传成功->picUrl = %@",picUrl);
            [self getCarMessageRequest];
        }
        else {
            [PopMsg showMessage:msg Lasttime:1.0f];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}


#pragma mark - 点击事件
- (void)backBtnClick {
    //编辑状态点击返回按钮返回非编辑状态
    if ([[_rightBtn currentTitle] isEqualToString:@"完成"]) {
        _uploadBtn.hidden = YES;
        _changeBtn.hidden = YES;
        [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    } else {
        if (_flag == 1) {
            [PopMsg showMessage:@"图片正在上传，请稍后返回" Lasttime:1.0f];
        } else if (_flag == 2) {
            [PopMsg showMessage:@"图片正在下载，请稍后返回" Lasttime:1.0f];
        } else if (_flag == 0) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)edit:(id)sender
{
    if ([self.userOrTourist isEqualToString:@"1"]) {
        //进入编辑状态
        if ([[_rightBtn currentTitle] isEqualToString:@"编辑"]) {
            if (_carImageView.image) {
                _changeBtn.hidden = NO;
                _uploadBtn.hidden = YES;
            }
            else {
                _uploadBtn.hidden = NO;
                _changeBtn.hidden = YES;
            }
            [_rightBtn setTitle:@"完成" forState:UIControlStateNormal];
        }
        //结束编辑状态(点击完成按钮)
        else {
            if (_carImageView.image) {
                [self uploadCarPicRequest];
            }
            else {
                
            }
            _uploadBtn.hidden = YES;
            _changeBtn.hidden = YES;
            [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
        }
    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
}

//点击照片放大照片
- (void)tapAction:(UIGestureRecognizer *)g
{
    _scaleView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT-20)];
    _scaleView.backgroundColor = [UIColor whiteColor];
    
    CGFloat largeH = SCREEN_WIDTH*_carImageView.image.size.height/_carImageView.image.size.width;
    UIImageView *largeImageView = [UIImageView new];
    if (largeH > SCREEN_HEIGHT-20) {
        largeImageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20);
    }
    else {
        largeImageView.frame = CGRectMake(0, (SCREEN_HEIGHT-20-largeH)/2, SCREEN_WIDTH, largeH);
    }
    
    [largeImageView setImage:_carImageView.image];
    largeImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBack:)];
    [largeImageView addGestureRecognizer:gesture];
    [_scaleView addSubview:largeImageView];
    [self.view addSubview:_scaleView];
    self.tabBarController.tabBar.hidden = YES;
}

//点击放大的照片恢复
- (void)tapBack:(UIGestureRecognizer *)gesture
{
    [_scaleView removeFromSuperview];
    self.tabBarController.tabBar.hidden = NO;
}

//上传车辆照片
- (void)uploadCarPic
{
    UIActionSheet *acSheet = [[UIActionSheet alloc]initWithTitle:@"选择图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从手机相册选择", nil];
    [acSheet showInView:self.view];
}

//更改车辆照片
- (void)changeCarPic
{
    UIActionSheet *acSheet = [[UIActionSheet alloc]initWithTitle:@"选择图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从手机相册选择", nil];
    [acSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //调用相机
    if (buttonIndex == 0) {
        NSLog(@"调用相机拍照");
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [self transferWithType:UIImagePickerControllerSourceTypeCamera];
        }else{
            NSLog(@"调用相机失败");
        }
    }
    //调用相册
    else if (buttonIndex == 1){
        NSLog(@"调用相册");
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [self transferWithType:UIImagePickerControllerSourceTypePhotoLibrary];
        }else{
            NSLog(@"调用相册失败");
        }
    }
}

//跳转方式(相机 or 相册？)
- (void)transferWithType:(UIImagePickerControllerSourceType)type {
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = type;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:^{
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"cancel");
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        CGFloat rate = image.size.width/image.size.height;
        if (rate > 1) {
            _carImageView.frame = _imageBgView.bounds;
        }
        else {
            _carImageView.frame = CGRectMake((CGRectGetWidth(_imageBgView.frame)-rate*167*H)/2, 0, rate*167*H, 167*H);
        }
        [_carImageView setImage:image];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        _uploadBtn.hidden = YES;
        _tipLabel.hidden = YES;
        _changeBtn.hidden = NO;
    }];
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
